/**
 * 用户等级系统
 * 处理等级升级所需的经验计算和等级提升逻辑
 */
import api from './api.js'
import menuManager from '../../systemDB/menu/menu.js'

// 基础经验配置
const BASE_EXPERIENCE = {
  1: 500,
  2: 1000,
  3: 2000,
  4: 4000
}

// 确保等级不会超过上限的辅助函数
function ensureMaxLevel(level) {
  return Math.min(level, getMaxLevel())
}

// 获取等级上限
async function getMaxLevel() {
  return await menuManager.getConfig('levelSystem', 'levelMax', 100)
}

// 获取经验增长倍数
async function getExperienceMultiplier() {
  return await menuManager.getConfig('levelSystem', 'levelMulti', 1.5)
}

/**
 * 获取升级到下一级所需的经验
 * @param {number} currentLevel - 当前等级
 * @returns {Promise<number>} 所需经验
 */
async function getRequiredExperience(currentLevel) {
  const MAX_LEVEL = await getMaxLevel();
  const EXPERIENCE_MULTIPLIER = await getExperienceMultiplier();

  if (currentLevel >= MAX_LEVEL) {
    return 0
  }

  if (currentLevel <= 3) {
    return BASE_EXPERIENCE[currentLevel + 1] || 0
  } else if (currentLevel === 4) {
    return BASE_EXPERIENCE[4] * EXPERIENCE_MULTIPLIER
  } else {
    // 4级以上每级经验是前一级的倍数
    return Math.floor(await getRequiredExperience(currentLevel - 1) * EXPERIENCE_MULTIPLIER)
  }
}

/**
 * 获取用户当前经验
 * @param {string} userId - 用户ID
 * @returns {Promise<number>} 当前经验
 */
async function getUserExperience(userId) {
  const experience = await api.getUserKeyValue(userId, 'levelExperience')
  return experience || 0
}

/**
 * 设置用户经验
 * @param {string} userId - 用户ID
 * @param {number} experience - 经验值
 * @returns {Promise<boolean>} 是否设置成功
 */
async function setUserExperience(userId, experience) {
  const result = await api.setUserKeyValue(userId, 'levelExperience', experience)
  return result.success
}

/**
 * 增加用户经验
 * @param {string} userId - 用户ID
 * @param {number} amount - 增加的经验值
 * @returns {Promise<{levelUp: boolean, newLevel: number, remainingExperience: number}>} 升级结果
 */
async function addUserExperience(userId, amount) {
  // 获取当前经验和等级
  let currentExperience = await getUserExperience(userId)
  let currentLevel = await api.getUserLevel(userId)

  // 确保等级不超过上限
  const MAX_LEVEL = await getMaxLevel();
  currentLevel = Math.min(currentLevel, MAX_LEVEL)

  // 增加经验
  currentExperience += amount

  // 检查是否可以升级
  let newLevel = currentLevel
  let remainingExperience = currentExperience

  // 如果未达到满级，检查是否可以升级
  if (currentLevel < MAX_LEVEL) {
    while (true) {
      const requiredExp = await getRequiredExperience(newLevel)
      if (requiredExp === 0 || remainingExperience < requiredExp) {
        break
      }

      // 升级
      newLevel += 1
      remainingExperience -= requiredExp

      // 如果达到满级，停止升级
      if (newLevel >= MAX_LEVEL) {
        newLevel = MAX_LEVEL
        break
      }
    }

    // 更新等级
    if (newLevel > currentLevel) {
      await api.addUserLevel(userId, newLevel - currentLevel)
    }
  } else {
    // 已达满级，保留所有经验
  }

  // 保存剩余经验
  await setUserExperience(userId, remainingExperience)

  return {
    levelUp: newLevel > currentLevel,
    newLevel: newLevel,
    remainingExperience: remainingExperience
  }
}

/**
 * 获取用户等级信息
 * @param {string} userId - 用户ID
 * @returns {Promise<{level: number, experience: number, nextLevelExperience: number}>} 等级信息
 */
async function getUserLevelInfo(userId) {
  let level = await api.getUserLevel(userId)
  // 确保返回的等级不超过上限
  const MAX_LEVEL = await getMaxLevel();
  level = Math.min(level, MAX_LEVEL)
  const experience = await getUserExperience(userId)
  const nextLevelExperience = level < MAX_LEVEL ? await getRequiredExperience(level) : 0

  return {
    level: level,
    experience: experience,
    nextLevelExperience: nextLevelExperience
  }
}

// 导出接口
export default {
  addUserExperience,
  getUserLevelInfo,
  getUserExperience,
  setUserExperience,
  getMaxLevel
}